package com.gitee.ly.chain.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.function.Consumer;

/**
 * ClassPathResourceUtil
 *
 * @author ly
 **/
public class ClassPathResourceUtil {
    public static InputStream getStream(String classpathFileAddress) {
        if (classpathFileAddress.startsWith("classpath:")) {
            classpathFileAddress = classpathFileAddress.replaceFirst("classpath:", "");
        }
        try {
            return Thread.currentThread().getContextClassLoader().getResourceAsStream(classpathFileAddress);
        } catch (Exception ex) {
            throw new RuntimeException("加载" + classpathFileAddress + "异常");
        }
    }

    public static void getStreamAndReadEveryLine(String classpathFileAddress, Consumer<String> lineReaderCosumer) {
        if (classpathFileAddress.startsWith("classpath:")) {
            classpathFileAddress = classpathFileAddress.replaceFirst("classpath:", "");
        }
        InputStream inputStream = null;
        try {
            inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(classpathFileAddress);
        } catch (Exception ex) {
            throw new RuntimeException("加载" + classpathFileAddress + "异常");
        }
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        try {
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                lineReaderCosumer.accept(line);
            }
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        } finally {
            try {
                bufferedReader.close();
                inputStreamReader.close();
                inputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
